<?php

namespace App\Http\Controllers\Systemparam;

use App\Http\Controllers\BaseController;
use App\Http\Validate\Systemparam\Systemparam;
use Illuminate\Http\Request;
use App\Models\Systemparam\Systemparam as ModelSystemparam;

/**
 * 系统参数管理
 */
class SystemparamController extends BaseController
{
    /**
     * 新增编辑
     */
    public function upsert(Request $request)
    {
        //校验参数
        $params = ['type', 'value'];
        $req_data = $request->only($params);
        $validate = new Systemparam('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        ModelSystemparam::updateOrInsert(
            ['cpid' => $cpid, 'type' => $req_data['type']],
            ['value' => $req_data['value'], 'create_at' => time()]
        );
        return response()->json(['code' => '000', 'msg' => '新增成功']);
    }

    /**
     * 获取
     */
    public function getone(Request $request)
    {
        //校验参数
        $params = ['type'];
        $req_data = $request->only($params);
        $validate = new Systemparam('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $one = ModelSystemparam::where(['cpid' => $cpid, 'type' => $req_data['type']])->first();
        if ($one) {
            $one = $one->toArray();
        } else {
            $one = [
                'type' => $req_data['type'],
                'value' => '',
            ];
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }
}
